/**
  ******************************************************************************
  * @文件     key.c
  * @作者     hero_cao
  * @版本     V1.0.0
  * @日期     2025/06/12
  * @概要     key底层驱动
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "./key/key.h"
#include "./board/bsp.h"


/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

/**
  * @brief  按键扫描
  * @param  mode-0不支持连按，1支持连按
  * @retval 按键值
  */
uint8_t key_scan(uint8_t mode)
{
	static uint8_t keyup = 1;  /* 按键按松开标志 */
	uint8_t keyval = 0;
	
	if(mode) keyup = 1;		/* 支持连按 */
	
	if (keyup && ((BSP_GpioRead(4) == 0) || (BSP_GpioRead(5) == 0) || (BSP_GpioRead(7) == 0) ||
					(BSP_GpioRead(8) == 0) || (BSP_GpioRead(9) == 0) || (BSP_GpioRead(10) == 0))) 
	{
		Delay_ms(5);           	/* 去抖动 */
		keyup = 0;
		if (BSP_GpioRead(4) == 0) keyval |= KEYA_PRES;
		if (BSP_GpioRead(5) == 0) keyval |= KEYB_PRES;
		if (BSP_GpioRead(7) == 0) {
			keyval |= UP_PRES;
		} else if (BSP_GpioRead(8) == 0) {
			keyval |= DOWN_PRES;
		}
		if (BSP_GpioRead(9) == 0) {
			keyval |= LEFT_PRES;
		} else if (BSP_GpioRead(10) == 0) {
			keyval |= RIGHT_PRES;
		}
	} else if ((BSP_GpioRead(4) == 1) && (BSP_GpioRead(5) == 1) && (BSP_GpioRead(7) == 1) &&
				(BSP_GpioRead(8) == 1) && (BSP_GpioRead(9) == 1) && (BSP_GpioRead(10) == 1))
	{
		keyup = 1;
	}
	
	return keyval;
}

/**
  * @brief  游戏按键扫描
  * @note   A B SELECT START UP DOWN LEFT RIGHT
  * @param  无
  * @retval 按键值
  */
uint8_t joy_scan(void)
{
	static uint8_t key_up = 1;  /* 按键按松开标志 */
	uint16_t key_evt_t = 0;		//按键事件
	uint8_t i,key_evt = 0;
	
	for (i = 3; i < 10; i++) {	
		if (BSP_GpioRead(i + 4) == 0) {
			key_evt_t |= 1 << (i+1);
		}
	}
	
	key_evt = ((key_evt_t >> 8) & 0x03) | key_evt_t;
	
	if (key_up && ((BSP_GpioRead(6) == 1) || (BSP_GpioRead(4) == 0) || (BSP_GpioRead(5) == 0))) {
		Delay_ms(2);           /* 去抖动 */
		key_up = 0;
		if (BSP_GpioRead(4) == 0) key_evt |= 0x01;
		if (BSP_GpioRead(5) == 0) key_evt |= 0x02;
		if (BSP_GpioRead(6) == 1) key_evt |= 0x08;
	} else if ((BSP_GpioRead(6) == 0) && (BSP_GpioRead(4) == 1) && (BSP_GpioRead(5) == 1)) {
		key_up = 1;
	}
	
	return key_evt;
}
